
package redbaydinelv;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.geom.RoundRectangle2D;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 *
 * @author Oriana Ramirez
 */
public class v_Vista extends javax.swing.JFrame
{   
    private javax.swing.JButton bEst;
    private javax.swing.JButton bSig;
    private javax.swing.JComboBox cbEst;
    private javax.swing.JCheckBox ckObs;
    private javax.swing.JCheckBox ckRel;
    private javax.swing.JLabel eCorTime;
    private javax.swing.JLabel eEst;
    private javax.swing.JLabel eRelTemp;
    private javax.swing.JLabel eSelArch;
    private javax.swing.JLabel eSelRelTemp;
    private javax.swing.JLabel eVarObs;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JPanel jpArchivo;
    private javax.swing.JPanel jpListNodos;
    private javax.swing.JPanel jpListRel;
    private javax.swing.JPanel jpRelTemp;
    private javax.swing.JScrollPane scrollPaneDer;
    private javax.swing.JScrollPane scrollPaneIzq;
    private javax.swing.JButton siguiente;
    private javax.swing.JTextField tCorTime;
    private javax.swing.JTextField tEst;
    private javax.swing.JButton bguardarPdf; 
    private javax.swing.JButton bguardarExcel;    
    private javax.swing.JLabel eVarTem;   
    private javax.swing.JPanel jpResInterno;
    private javax.swing.JPanel jpResultados;    
    private javax.swing.JScrollPane scrollResultados;
    private javax.swing.JScrollPane scrollTablVal;   
    private javax.swing.JTable tVal;
    private javax.swing.JProgressBar barraProgreso;
    
    String tem1;  
    boolean b = false;
    
    List<javax.swing.JCheckBox> ckRelacion;
    List<javax.swing.JCheckBox> ckObservar;        
    List<JComboBox> cbEstados;
    List<javax.swing.JLabel> eListVarTem;
    List<javax.swing.JTable> tablListVarTem;
    List<javax.swing.JScrollPane> scrollListVarTem;
        
    c_Nodos c_nodos;
    
    public v_Vista()
    {
        PestanaArchivo();
    }
    
    private void PestanaArchivo() 
    {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jpArchivo = new javax.swing.JPanel();
        eSelArch = new javax.swing.JLabel();
        eEst = new javax.swing.JLabel();
        tEst = new javax.swing.JTextField();
        bEst = new javax.swing.JButton();
        eCorTime = new javax.swing.JLabel();
        tCorTime = new javax.swing.JTextField();
        bSig = new javax.swing.JButton();
        
        tem1 = null;

        setTitle("Aplicación para Redes Bayesianas Dinámicas");
        setBounds(30, 50, 600, 450); 
        setResizable(false);
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTabbedPane1.setPreferredSize(new java.awt.Dimension(600, 450));

        jpArchivo.setPreferredSize(new java.awt.Dimension(600, 450));

        eSelArch.setFont(new java.awt.Font("Tahoma", 0, 14)); 
        eSelArch.setText("Seleccione la Estructura Estática y los Cortes de Tiempo de la Red Bayesiana Dinámica");

        eEst.setFont(new java.awt.Font("Tahoma", 0, 12)); 
        eEst.setText("Estructura de la Red Bayesiana: ");

        tEst.setFont(new java.awt.Font("Tahoma", 0, 12)); 
        tEst.setText("Direccion Local");
        tEst.setForeground(new java.awt.Color(204, 204, 204));
        tEst.setEditable(true); 
        tEst.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                if(tEst.getText().compareTo("Direccion Local") == 0){
                    tEst.setText("");
                    tEst.setForeground(new java.awt.Color(0, 0, 0));
                }
            }
        });

        bEst.setFont(new java.awt.Font("Tahoma", 0, 12));
        bEst.setText("Examinar");
        bEst.addActionListener(new java.awt.event.ActionListener() 
        {
            public void actionPerformed(java.awt.event.ActionEvent evt) 
            {
                JFileChooser buscar = new JFileChooser();
                int opcion = buscar.showOpenDialog(jpArchivo);          

                if(opcion == JFileChooser.APPROVE_OPTION)
                {
                    tem1 = buscar.getSelectedFile().getPath();
                    tEst.setText(tem1);
                    tEst.setForeground(new java.awt.Color(0, 0, 0));
                } 
            }
        });

        eCorTime.setFont(new java.awt.Font("Tahoma", 0, 12)); 
        eCorTime.setText("Cortes de Tiempo: ");

        tCorTime.setFont(new java.awt.Font("Tahoma", 0, 12));
        tCorTime.setEditable(true);
        tCorTime.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                char car = evt.getKeyChar();
                if((car<'0' || car>'9')) 
                    evt.consume();
            }
        });
        

        bSig.setFont(new java.awt.Font("Tahoma", 0, 12)); 
        bSig.setText("Siguiente");
        bSig.addActionListener(new java.awt.event.ActionListener() 
        {
            public void actionPerformed(java.awt.event.ActionEvent evt) 
            {
                c_nodos = new c_Nodos();
                if((!"Direccion Local".equals(tEst.getText())) && (!"".equals(tCorTime.getText())) && jTabbedPane1.getTabCount() <= 1 && (Integer.parseInt(tCorTime.getText()) > 0))
                { 
                    tem1 = tEst.getText();
                //Añade al JTabbed Pestañas
                    PestanaRelTem(tem1);                                      
                //Cambiar a la pestaña Relacion Temporal
                    jTabbedPane1.setSelectedIndex(1);                    
                }
                else if(("Direccion Local".equals(tEst.getText())) || ("".equals(tCorTime.getText())))
                {
                    JOptionPane.showMessageDialog(null, "Debes ingresar la estructura de la red bayesiana y los cortes de tiempo deben ser mayor a cero");
                }
                else if((!"Direccion Local".equals(tEst.getText())) && (!"".equals(tCorTime.getText())) && jTabbedPane1.getTabCount() > 1 && (Integer.parseInt(tCorTime.getText()) > 0))
                {
                //Añade al JTabbed Pestañas
                    PestanaRelTem(tem1);                
                //Cambiar a la pestaña Relacion Temporal
                    jTabbedPane1.setSelectedIndex(1);
                }
            }
        });

        javax.swing.GroupLayout jpArchivoLayout = new javax.swing.GroupLayout(jpArchivo);
        jpArchivo.setLayout(jpArchivoLayout);
        jpArchivoLayout.setHorizontalGroup(
            jpArchivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpArchivoLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(eSelArch)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jpArchivoLayout.createSequentialGroup()
                .addGroup(jpArchivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jpArchivoLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(bSig, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jpArchivoLayout.createSequentialGroup()
                        .addGap(38, 38, 38)
                        .addGroup(jpArchivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(tCorTime, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(eCorTime, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(eEst, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jpArchivoLayout.createSequentialGroup()
                                .addComponent(tEst, javax.swing.GroupLayout.PREFERRED_SIZE, 431, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(11, 11, 11)
                                .addComponent(bEst)))))
                .addContainerGap(34, Short.MAX_VALUE))
        );
        jpArchivoLayout.setVerticalGroup(
            jpArchivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpArchivoLayout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(eSelArch)
                .addGap(41, 41, 41)
                .addComponent(eEst)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpArchivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(bEst, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(tEst))
                .addGap(38, 38, 38)
                .addComponent(eCorTime)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tCorTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 125, Short.MAX_VALUE)
                .addComponent(bSig)
                .addGap(80, 80, 80))
        );

        jTabbedPane1.addTab("Cargar Red", null, jpArchivo, "");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }
    
    public void PestanaRelTem(String ruta)
    {
        jpRelTemp = new javax.swing.JPanel();
        eSelRelTemp = new javax.swing.JLabel();
        scrollPaneIzq = new javax.swing.JScrollPane();
        jpListRel = new javax.swing.JPanel();        
        scrollPaneDer = new javax.swing.JScrollPane();
        jpListNodos = new javax.swing.JPanel();
        eRelTemp = new javax.swing.JLabel();
        eVarObs = new javax.swing.JLabel();
        siguiente = new javax.swing.JButton();
        barraProgreso = new javax.swing.JProgressBar();
        
        int dimXRel = 0;
        int dimXObs = 0;
        
        ckRelacion = new ArrayList<>();
        ckObservar = new ArrayList<>();        
        cbEstados = new ArrayList<>();
        
        c_nodos.LeerRedEstatica(ruta);
        
        jpRelTemp.setPreferredSize(new java.awt.Dimension(600, 450));

        eSelRelTemp.setFont(new java.awt.Font("Tahoma", 0, 14)); 
        eSelRelTemp.setText("Seleccione las Relaciones Temporales y las Variables de Observación");

// PANEL IZQUIERDO
        
        for(int j = 0; j < c_nodos.getEnlaces().size(); j ++)
        {
            if(c_nodos.getEnlaces().get(j).length() > dimXRel)
            {
                dimXRel = c_nodos.getEnlaces().get(j).length();
            }
        }
        
        scrollPaneIzq.setPreferredSize(new java.awt.Dimension(225, 250));

        jpListRel.setPreferredSize(new java.awt.Dimension(20 + (dimXRel * 7) + 10, 10 + (c_nodos.getEnlaces().size() * 30)));

        for(int j = 0; j < c_nodos.getEnlaces().size(); j ++)
        {
            ckRel = new javax.swing.JCheckBox();
            ckRel.setText(c_nodos.getEnlaces().get(j));            
            ckRel.setBounds(20, 10 + (j * 30), (dimXRel * 7), 20);               
            ckRel.setPreferredSize(new java.awt.Dimension((dimXRel * 7), 20));
            ckRelacion.add(ckRel); 
            
            jpListRel.add(ckRelacion.get(j));
            
            javax.swing.GroupLayout jpListRelLayout = new javax.swing.GroupLayout(jpListRel);
            jpListRel.setLayout(jpListRelLayout);
        }
        
        scrollPaneIzq.setViewportView(jpListRel);

// PANEL DERECHO
        for(int j = 0; j < c_nodos.getLNodos().size(); j ++)
        {
            if(c_nodos.getLNodos().get(j).getName().length() > dimXObs)
            {
                dimXObs = c_nodos.getLNodos().get(j).getName().length();
            }
        }
        
        scrollPaneDer.setPreferredSize(new java.awt.Dimension(225, 250));

        jpListNodos.setPreferredSize(new java.awt.Dimension(20 + (dimXObs * 7) + 10 + 50 + 10,  10 + (c_nodos.getLNodos().size() * 30)));

        for(int j = 0; j < c_nodos.getLNodos().size(); j ++)
        {
            ckObs = new javax.swing.JCheckBox();
            ckObs.setText(c_nodos.getLNodos().get(j).getName());
            ckObs.setBounds(20, 10 + (j * 30), (dimXObs * 7), 20);  
            ckObs.setPreferredSize(new java.awt.Dimension((dimXObs * 7), 20));
            ckObservar.add(ckObs);
            
            jpListNodos.add(ckObservar.get(j));
            
            cbEst = new javax.swing.JComboBox();
            cbEst.setBounds(20 + (dimXObs * 7) + 10, 10 + (j * 30), 50, 20); 
            cbEst.setPreferredSize(new java.awt.Dimension(50, 20));
            cbEst.setModel(new javax.swing.DefaultComboBoxModel(c_nodos.getEstadosS(c_nodos.getLNodos().get(j).getName())));            
            cbEstados.add(cbEst);            
            
            jpListNodos.add(cbEstados.get(j));  
            
            javax.swing.GroupLayout jpListNodosLayout = new javax.swing.GroupLayout(jpListNodos);
            jpListNodos.setLayout(jpListNodosLayout);                  
        }

        scrollPaneDer.setViewportView(jpListNodos);

        eRelTemp.setFont(new java.awt.Font("Tahoma", 0, 12)); 
        eRelTemp.setText("Relaciones Temporales:");

        eVarObs.setFont(new java.awt.Font("Tahoma", 0, 12));
        eVarObs.setText("Variables de Observación:");

        siguiente.setText("Siguiente");
        siguiente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                
                List<String> lsRelTem1 = new ArrayList<>();
                List<String> lsRelTem2 = new ArrayList<>();
                List<String> lsVarObs = new ArrayList<>();
                List<String> lsEstObs = new ArrayList<>();
                                
                int banderaRel = 0;
                int banderaObs = 0;
    
                for (int i = 0; i < ckRelacion.size(); i++) 
                {
                    if(ckRelacion.get(i).isSelected() == true)
                    {
                        lsRelTem1.add(ckRelacion.get(i).getText().split(" --> ")[0]);
                        lsRelTem2.add(ckRelacion.get(i).getText().split(" --> ")[1]);
                        banderaRel ++;
                    }
                }
                
                for (int i = 0; i < ckObservar.size(); i++) 
                {
                    if(ckObservar.get(i).isSelected() == true)
                    {
                        lsVarObs.add(ckObservar.get(i).getText());
                        lsEstObs.add(cbEstados.get(i).getSelectedItem().toString());
                        banderaObs ++;
                    }
                }
                
                if(banderaRel == 0 && banderaObs == 0)
                {
                    JOptionPane.showMessageDialog(null, "Debes seleccionar por lo menos una Relación Temporal y una Variable de Observación");
                }else if(banderaRel == 0 && banderaObs > 0)
                {
                    JOptionPane.showMessageDialog(null, "Debes seleccionar por lo menos una Relación Temporal y una Variable de Observación");
                }else if(banderaRel > 0 && banderaObs == 0)
                {
                    JOptionPane.showMessageDialog(null, "Debes seleccionar por lo menos una Relación Temporal y una Variable de Observación");
                }else
                {     
                    c_nodos.CargarDatos(lsRelTem1, lsRelTem2, lsVarObs, lsEstObs, Integer.parseInt(tCorTime.getText()));
                    c_nodos.run();
                    new Thread(new jcThread( barraProgreso, false)).start();
                    jTabbedPane1.addTab("Resultados", PestanaResultados(lsRelTem1, lsRelTem2, lsVarObs, lsEstObs, Integer.parseInt(tCorTime.getText()))); 
                    jTabbedPane1.setSelectedIndex(2);                   
                }
            }
        });

        javax.swing.GroupLayout jpRelTempLayout = new javax.swing.GroupLayout(jpRelTemp);
        jpRelTemp.setLayout(jpRelTempLayout);
        jpRelTempLayout.setHorizontalGroup(
            jpRelTempLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpRelTempLayout.createSequentialGroup()
                .addGap(95, 95, 95)
                .addComponent(eSelRelTemp)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpRelTempLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jpRelTempLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(barraProgreso, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jpRelTempLayout.createSequentialGroup()
                        .addGroup(jpRelTempLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(eRelTemp)
                            .addComponent(scrollPaneIzq, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(50, 50, 50)
                        .addGroup(jpRelTempLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jpRelTempLayout.createSequentialGroup()
                                .addGap(148, 148, 148)
                                .addComponent(siguiente))
                            .addComponent(eVarObs)
                            .addComponent(scrollPaneDer, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))))
                .addGap(50, 50, 50))
        );
        jpRelTempLayout.setVerticalGroup(
            jpRelTempLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpRelTempLayout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addComponent(eSelRelTemp)
                .addGap(25, 25, 25)
                .addGroup(jpRelTempLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(eRelTemp)
                    .addComponent(eVarObs))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpRelTempLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(scrollPaneIzq, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(scrollPaneDer, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addGap(13, 13, 13)
                .addComponent(barraProgreso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(3, 3, 3)
                .addComponent(siguiente)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Relaciones Temporales", jpRelTemp);
    }
    
    public javax.swing.JPanel PestanaResultados(List<String> RelNodo1, List<String> RelNodo2, List<String> Observar, List<String> Estados, int Tiempo)
    {
//Resultados Inferencia   
        jpResultados = new javax.swing.JPanel();
        scrollResultados = new javax.swing.JScrollPane();
        jpResInterno = new javax.swing.JPanel();
        bguardarPdf = new javax.swing.JButton();
        bguardarExcel = new javax.swing.JButton();
        eVarTem = new javax.swing.JLabel();
        scrollTablVal = new javax.swing.JScrollPane();
        tVal = new javax.swing.JTable();
        
        eListVarTem = new ArrayList<>();
        tablListVarTem = new ArrayList<>();
        scrollListVarTem = new ArrayList<>();

        int posVarT = 60;
        int posTabV = 90;
                                
        jpResultados.setPreferredSize(new java.awt.Dimension(600, 450));
		
        scrollResultados.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scrollResultados.setPreferredSize(new java.awt.Dimension(600, 425));

        jpResInterno.setPreferredSize(new java.awt.Dimension(600, (282 * c_nodos.getListResultados().get(0).size())));

        bguardarPdf.setText("Guardar PDF");
        bguardarPdf.setBounds(445, 30, 100, 35);
        bguardarPdf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                File rutDest = null;
                
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivo PDF","pdf","PDF");
                JFileChooser fileChooser = new JFileChooser();       
                fileChooser.setFileFilter(filter);
                int result = fileChooser.showSaveDialog(null);
                if ( result == JFileChooser.APPROVE_OPTION ){   
                    rutDest = fileChooser.getSelectedFile().getAbsoluteFile();
                }
                
                if(rutDest != null){            
                    
                    try {            
                        
                        Document pdf = new Document(PageSize.LETTER, 80, 80, 75, 75);
                        try {
                            try {
                                PdfWriter.getInstance(pdf, new FileOutputStream(rutDest + ".pdf"));
                            } catch (DocumentException ex) {
                                Logger.getLogger(v_Vista.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger(v_Vista.class.getName()).log(Level.SEVERE, null, ex);
                        }

                        pdf.open();
                        Paragraph titulo = new Paragraph("Red Bayesiana Dinámica: ".concat(c_nodos.NombreRed.toUpperCase()), new Font(Font.FontFamily.COURIER, 16, Font.BOLDITALIC));
                        titulo.setAlignment(1);
                        pdf.add(titulo);
                        pdf.add(new Paragraph(" "));
                        pdf.add(new Paragraph(" "));
                        for (int i = 0; i < eListVarTem.size(); i++) {
                            pdf.add(new Paragraph(eListVarTem.get(i).getText()));
                            pdf.add(new Paragraph(" "));
                            
                            PdfPTable tab = new PdfPTable(tablListVarTem.get(i).getColumnCount());                            
                            for (int l = 0; l < tablListVarTem.get(i).getColumnCount(); l++) {
                                PdfPCell celda = new PdfPCell((new Phrase(tablListVarTem.get(i).getColumnName(l),new Font(Font.FontFamily.COURIER, 12, Font.BOLDITALIC))));
                                celda.setVerticalAlignment(Element.ALIGN_CENTER);
                                celda.setHorizontalAlignment(Element.ALIGN_CENTER);                               
                                tab.addCell(celda);
                            }                            
                            for (int j = 0; j < tablListVarTem.get(i).getRowCount(); j++) {
                                for (int k = 0; k < tablListVarTem.get(i).getColumnCount(); k++) {
                                    tab.addCell(tablListVarTem.get(i).getModel().getValueAt(j, k).toString());
                                }                                
                            }
                            pdf.add(tab);
                            pdf.add(new Paragraph(" "));
                            pdf.add(new Paragraph(" "));
                        }                 
                        
                        pdf.close();
                        JOptionPane.showMessageDialog(null,"Documento PDF creado");
                        
                    } catch (DocumentException ex) {
                        JOptionPane.showMessageDialog(null, "No se pudo crear el archivo PDF, intente de nuevo");
                    }                        
                } 
            }
        });
        
        bguardarExcel.setText("Guardar EXCEL");
        bguardarExcel.setBounds(305, 30, 120, 35);
        bguardarExcel.addActionListener(new java.awt.event.ActionListener(){
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                File rutDest = null;
                
                JFileChooser fileChooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivos XLS", "xls", "csv");                       
                fileChooser.setFileFilter(filter);
                int result = fileChooser.showSaveDialog(null);
                if ( result == JFileChooser.APPROVE_OPTION ){   
                    rutDest = fileChooser.getSelectedFile().getAbsoluteFile();
                }
                
                if(rutDest != null){
                    HSSFWorkbook libro = new HSSFWorkbook();
                    
                    for (int i = 0; i < eListVarTem.size(); i++) {                        
                        HSSFSheet hoja = libro.createSheet(eListVarTem.get(i).getText().substring(1 + eListVarTem.get(i).getText().indexOf(":"), eListVarTem.get(i).getText().length()));                
                        
                        HSSFRow filaNombres = hoja.createRow(0);                          
                        for (int l = 0; l < tablListVarTem.get(i).getColumnCount(); l++) {                            
                            HSSFCell celda = filaNombres.createCell(l);
                            celda.setCellValue(tablListVarTem.get(i).getColumnName(l));   
                            hoja.autoSizeColumn(l);
                        } 
                        
                        for (int j = 0; j < tablListVarTem.get(i).getRowCount(); j++) {
                            HSSFRow filaValores = hoja.createRow(j + 1);
                            for (int k = 0; k < tablListVarTem.get(i).getColumnCount(); k++) {                                
                                HSSFCell celda = filaValores.createCell(k);
                                //tablListVarTem.get(i).getModel().getValueAt(j, k).toString().replace(".", ",")
                                celda.setCellValue(Double.parseDouble(tablListVarTem.get(i).getModel().getValueAt(j, k).toString()));
                            }                                
                        }
                    }             
                    try {
                        FileOutputStream excel = new FileOutputStream(rutDest + ".xls");
                        try {
                            libro.write(excel);
                            excel.close();
                        } catch (IOException ex) {
                            JOptionPane.showMessageDialog(null, "No se pudo crear el archivo XLS, intente de nuevo");
                        }
                        JOptionPane.showMessageDialog(null,"Documento XLS creado");
                    } catch (FileNotFoundException ex) {
                        JOptionPane.showMessageDialog(null, "No se pudo crear el archivo XLS, intente de nuevo");
                    }
                    
                                    
                }
            
            }
        });
        
        jpResInterno.add(bguardarPdf);
        jpResInterno.add(bguardarExcel);
        
        for(int i = 0; i < c_nodos.getListResultados().get(0).size(); i ++)
        {		
            eVarTem = new javax.swing.JLabel();
            eVarTem.setFont(new java.awt.Font("Tahoma", 0, 14)); 
            eVarTem.setText("Variable Temporal: ".concat(c_nodos.getListResultados().get(0).get(i).getVariableTemporal()));
            eVarTem.setBounds(50, posVarT, 250, 20);

            String[][] matrizVal = new String [Tiempo][1 + c_nodos.getListResultados().get(0).get(i).getEstados().length];

            for(int j = 0; j < Tiempo; j++)
            {
                matrizVal[j][0] = Integer.toString(j+1); 		
                for(int h = 1; h <= c_nodos.getListResultados().get(0).get(i).getEstados().length; h++)
                {
                        matrizVal[j][h] = Double.toString(c_nodos.getListResultados().get(j).get(i).getValores()[h-1]);
                }
            }

            String[] vecTitTab = new String [1 + c_nodos.getListResultados().get(0).get(i).getEstados().length];
            vecTitTab[0] = "TIEMPO";
            for(int l = 1; l <= c_nodos.getListResultados().get(0).get(i).getEstados().length; l++)
            {
                vecTitTab[l] = c_nodos.getListResultados().get(0).get(i).getEstados()[l-1].getName().toUpperCase();
            }

            scrollTablVal = new javax.swing.JScrollPane();
            scrollTablVal.setPreferredSize(new java.awt.Dimension(500, 162));

            tVal = new javax.swing.JTable();
            tVal.setFont(new java.awt.Font("Tahoma", 0, 12)); 
            tVal.setBounds(50, posTabV, 70 * (1 + c_nodos.getListResultados().get(0).get(i).getEstados().length), (16 * Tiempo));
            tVal.setModel(new javax.swing.table.DefaultTableModel( matrizVal, vecTitTab));
            tVal.setPreferredSize(new java.awt.Dimension(70 * (1 + c_nodos.getListResultados().get(0).get(i).getEstados().length), (16 * Tiempo)));	

            tablListVarTem.add(tVal);

            scrollTablVal.setBounds(50, posTabV, 500, 162);
            scrollTablVal.setViewportView(tablListVarTem.get(i));

            scrollListVarTem.add(scrollTablVal);
            
            posVarT += 222;
            posTabV += 222;

            eListVarTem.add(eVarTem);

            jpResInterno.add(eListVarTem.get(i));
            jpResInterno.add(scrollListVarTem.get(i));
            
            javax.swing.GroupLayout jpResInternoLayout = new javax.swing.GroupLayout(jpResInterno);
            jpResInterno.setLayout(jpResInternoLayout);           
        }    
        
        scrollResultados.setViewportView(jpResInterno);

        javax.swing.GroupLayout jpResultadosLayout = new javax.swing.GroupLayout(jpResultados);
        jpResultados.setLayout(jpResultadosLayout);
        
        jpResultadosLayout.setHorizontalGroup(
            jpResultadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(scrollResultados, javax.swing.GroupLayout.PREFERRED_SIZE, 600, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        jpResultadosLayout.setVerticalGroup(
            jpResultadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(scrollResultados, javax.swing.GroupLayout.PREFERRED_SIZE, 425, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        
        return jpResultados;
        //jTabbedPane1.addTab("Resultados", jpResultados);     
    }
    public static void main(String args[]) {
        
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(v_Vista.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        //</editor-fold>
        
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new v_Vista().setVisible(true);
            }
        });
    }    
}


